
use std::rc::{Rc, Weak};
use std::cell::RefCell;

#[derive(Debug)]
struct Node {
    value : i32,
    parent: RefCell<Weak<Node>>,
    children : RefCell<Vec<Rc<Node>>>,
}

#[test] // 注意添加 -- nocapture
fn test_tree () {
    // 这是叶节点
    let leaf = Rc::new(Node {
        value: 3,
        // 创建一个弱引用的Weak智能指针
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });
    // println!("Leaf parent = {:?} , that before set parent point.", leaf.parent.borrow().upgrade());
    println!("Leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf));
    println!("这是后 Leaf parent 没有值 = {:?}", leaf.parent.borrow().upgrade());
    {
        // 这是枝干节点
        let branch = Rc::new(Node {
            value: 5,
            // 这个Week指针之后将指向它的父节点 , Weak::new() 会创建一个 Weak<None> 的引用
            parent: RefCell::new(Weak::new()),
            children: RefCell::new(vec![Rc::clone(&leaf)]),
        });

        // 将leaf （叶节点）的parent 指向 branch
        *leaf.parent.borrow_mut() = Rc::downgrade(&branch);

        println!("Branch strong = {}, weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch));
        println!("Leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf));
        //
        println!("这是后 Leaf parent 有值了哦 = {:?}", leaf.parent.borrow().upgrade());
    }
    println!("===== 作用域离开后，branch就被干掉了");
    println!("Leaf parent = {:?}", leaf.parent.borrow().upgrade());
    println!(
        "Leaf strong = {}, weak = {}",
        Rc::strong_count(&leaf),
        Rc::weak_count(&leaf),
    );
    println!("你可以发现，当作用域离开后，此时的Branch strong=1,weak=1，但是Branch还是被销毁了，虽然weak 在此时持有这leaf 的引用。");
}